<?php
declare (strict_types = 1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use addons\Target\facade\Target;
use addons\V2\admin\model\Order;
use app\common\model\Relation;
use think\facade\Cache;
use think\facade\View;
use think\response\Json;

//该文件为自动生成，请按需修改
class AgentBonus extends Base
{
    //所有定义变量均为演示，请根据实际需求更改

    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\AgentBonus';


    public function index(): string
    {
        //构建表格数据
        return Builder::Table()
            ->addColumn(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80, 'fixed' => 'left'])
            ->addColumn(['field' => 'performance', 'title' => '业绩'])
            ->addColumn(['field' => 'total_amount', 'title' => '分红金额'])
            ->addColumn(['field' => 'num', 'title' => '分红人数'])
            ->addColumn(['field' => 'amount', 'title' => '应发金额'])
            ->addColumn(['field' => 'actual', 'title' => '实发金额'])
            ->addColumn(['field' => 'create_time', 'title' => '分红时间'])
            ->addTopButtons([
                'add' => [
                    'title' => '代理分红',
                    'size' => '60%'
                ]
            ])
//            ->addColumn(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 200])
//            ->addRightButtons(['edit' => ['title' => '查看', 'unity_title' => '审核/查看', 'size' => '60%']])
//            ->addSearch([
//                ['title', '等级名称搜索', 'input,Like'],
//            ],false)
            ->fetch();
    }

    public function add($id = '', $tpl = 'agent_bonus/add', $info = ''): string
    {
//        $bonus = 0;
        $num = \app\common\model\User::where(['level_id'=>7,'delete_time'=>0])->count();//总人数
        $amount = \app\common\model\User::where('newly_total','>',0)->sum('newly_total');//新增业绩
        $agent_bonus = Cache::get('system')['agent_bonus'];
        $total_amount = bcmul((string)$amount, (string)$agent_bonus, 2);//分红金额
        if($num==0)
        {
            $user_bonus = 0;//应发金额
        }else{
            $user_bonus = bcdiv((string)$total_amount, (string)$num, 2);//应发金额
        }

        View::assign(['num'=>$num,'amount'=>$amount,'total_amount'=>$total_amount,'user_bonus'=>$user_bonus]);
        return View::fetch();// TODO: Change the autogenerated stub
    }


    public function save($param = [], $model = true): Json
    {
        $param = $this->request->param();
        \app\common\model\AgentBonus::create($param);
        $user = \app\common\model\User::where(['level_id'=>7,'delete_time'=>0])->column('id');
        foreach ($user as $key=>$value)
        {
            Target::Account()->basics($value, 'reward', $param['actual'], '代理分红', '+')
                ->createBonus($value, 7);
        }
        return json(['code'=>1,'msg'=>'发放成功']);
    }

}
